﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace GenBenEditor
{
    public class Map
    {
        public const uint width = 256;
        public const uint height = 256;

        private char[] magic_letters = {'M', 'A', 'P'};
        private byte version = 0;

        public List<Tileset> tilesets;
        public List<Page> pages;
        public Page[,] positioned_pages;

        public string path = "";

        public Map()
        {
            tilesets = new List<Tileset>();
            pages = new List<Page>();
            positioned_pages = new Page[height, width];
        }

        public void Load(string path)
        {
            this.path = path;

            FileStream input = new FileStream(path, FileMode.Open);
            BinaryReader reader = new BinaryReader(input);

            //Debug.Assert(reader.ReadChars(3) == magic_letters);
            //Debug.Assert(reader.ReadByte() == version);
            char[] chars = reader.ReadChars(3);
            byte version = reader.ReadByte();
            

            byte n_tilesets = reader.ReadByte();
            while (n_tilesets-- > 0)
            {
                tilesets.Add(new Tileset(reader.ReadString()));
            }

            UInt16 n_pages = reader.ReadUInt16();
            while (n_pages-- > 0)
            {
                Page new_page = new Page();
                new_page.Deserialize(reader);
                pages.Add(new_page);

                Debug.Assert(positioned_pages[new_page.y, new_page.x] == null);
                positioned_pages[new_page.y, new_page.x] = new_page;
            }

            reader.Close();
        }

        public void Save(string path)
        {
            this.path = path;

            FileStream output = new FileStream(path, FileMode.Create);
            BinaryWriter writer = new BinaryWriter(output);

            writer.Write(magic_letters);
            writer.Write(version);
            writer.Write((byte)(tilesets.Count));
            foreach(Tileset tileset in tilesets)
            {
                writer.Write(tileset.path);
            }

            writer.Write((byte)(pages.Count));
            foreach (Page page in pages)
            {
                page.Serialize(writer);
            }

            writer.Close();
        }
    }
}
